package com.zeus.common.utils;

import com.zeus.common.log.ZeusLoggerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

/**
 * 工程工具
 *
 * @author wangfeixiong126@gmail.com  2021/5/14 19:37
 */
public class ProjectUtils {
    private final static Logger logger = LoggerFactory.getLogger(ProjectUtils.class);

    /**
     * 部署tag号
     */
    private static String DEPLOY_TAG = null;
    /**
     * 获取TAG错误次数统计
     */
    private static int GET_TAG_ERROR_COUNT = 0;
    /**
     * 获取TAG最大错误次数
     */
    private static final int GET_TAG_ERROR_COUNT_MAX = 2;

    /**
     * 获取部署tag
     * 
     * @return tag
     * @author wangfeixiong126@gmail.com  2021/5/14 19:37
     */
    public static String getDeployTag() {
        if (DEPLOY_TAG != null && !DEPLOY_TAG.isEmpty()) {
            // 直接返回
            return DEPLOY_TAG;
        }
        if (GET_TAG_ERROR_COUNT >= GET_TAG_ERROR_COUNT_MAX) {
            // 获取失败次数过多，则直接返回
            return DEPLOY_TAG;
        }

        try {
            for (int i = 0; i < GET_TAG_ERROR_COUNT_MAX; i++) {
                String path = getDeployTagPath();
                try (BufferedReader reader = new BufferedReader(new FileReader(new File(path)))) {
                    String readLine = reader.readLine();
                    if (readLine != null && !readLine.isEmpty()) {
                        DEPLOY_TAG = readLine;
                        return DEPLOY_TAG;
                    }
                } catch (Exception e) {
                    if (logger.isWarnEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                        logger.warn("### Zeus报警服务, 获取部署tag失败 >> errMsg = {}", e.getMessage());
                    }
                    GET_TAG_ERROR_COUNT++;
                }
            }
        } catch (Throwable t) {
            if (logger.isWarnEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                logger.warn("### Zeus报警服务, 获取部署tag失败 >> errMsg = {}", t.getMessage());
            }
        }
        return DEPLOY_TAG;
    }

    /**
     * <p>Title: getDeployTagPath. </p>
     * <p>Description: 获取项目Tag文件存储路径 </p>
     * 
     * @return tag文件路径
     * @author wangfeixiong126@gmail.com  2021/8/18 6:11 下午
     */
    private static String getDeployTagPath() {
        String path = System.getProperty("user.dir") + File.separator + "GIT_VERSION";
        try {
            if (GET_TAG_ERROR_COUNT > 0) {

            }
        } catch (Throwable ignored) {
            // 忽略
        }
        return path;
    }
}
